package org.webscale.http;
import java.io.IOException;

import junit.framework.TestCase;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.Logger;

public class TestHttpGet extends TestCase{
	private static final Logger log = Logger.getLogger(TestHttpGet.class);

	// public static String url = "http://www.melissadata.com/lookups/zipstreet.asp?Step4=93063&Name=ABILENE";
	 private String urlPattern = "http://www.melissadata.com/lookups/zipstreet.asp?Step4=$zip$&Name=$street$";
	
	public void testGet(){
		
		String tzip = "93063";
		String szip = "$zip$";
		
		String tstreet = "ABILENE";
		String sstreet = "$street$";
		
		String url = urlPattern.replace(szip, tzip);
		url = url.replace(sstreet ,tstreet);
		
		System.out.println("URL =" + url);
		
		 // Create an instance of HttpClient.
	    HttpClient client = new HttpClient();

	    // Create a method instance.
	    GetMethod method = new GetMethod(url);
	    
	    // Provide custom retry handler is necessary
	    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
	    		new DefaultHttpMethodRetryHandler(3, false));

	    try {
	      // Execute the method.
	      int statusCode = client.executeMethod(method);

	      if (statusCode != HttpStatus.SC_OK) {
	        System.err.println("Method failed: " + method.getStatusLine());
	      }

	      // Read the response body.
	      byte[] responseBody = method.getResponseBody();

	      // Deal with the response.
	      // Use caution: ensure correct character encoding and is not binary data
	      System.out.println(new String(responseBody));

	    } catch (HttpException e) {
	      System.err.println("Fatal protocol violation: " + e.getMessage());
	      e.printStackTrace();
	    } catch (IOException e) {
	      System.err.println("Fatal transport error: " + e.getMessage());
	      e.printStackTrace();
	    } finally {
	      // Release the connection.
	      method.releaseConnection();
	    }  

	}
	
}
